//
//  AuthenCompanyFYVC.swift
//  kxf
//
//  Created by Elavatine on 2024/11/21.
//


import Foundation
import UIKit
import MCToast

class AuthenCompanyFYVC: WHBaseViewVC {
    
    var type = COMPANY_AUTHEN_MSG_TYPE.merc
    
    var isUpdate = false
    //是否为只读模式
    var isRead = false
    //是否为代理商帮忙填写信息
    var isAgentEdit = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        if isUpdate{
            mercMsgVm.updateUIForRefuse()
            mercLegalVm.updateUIForRefuse()
            settleVm.updateUIForRefuse()
            marketVm.updateUIForRefuse()
        }
        if isRead{
            mercMsgVm.setReadMode()
            mercLegalVm.setReadMode()
            settleVm.setReadMode()
            marketVm.setReadMode()
            saveBtn.isHidden = true
            marketVm.nextBtn.isHidden = true
        }
    }
    lazy var saveBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        
        btn.addTarget(self, action: #selector(saveAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var typeVm : AuthenTopTypeCompanyVM = {
        let vm = AuthenTopTypeCompanyVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: 0, height: 0))
        vm.typeChangeBlock = {(type)in
            self.type = type
            switch self.type{
            case .merc:
                self.mercMsgVm.isHidden = false
                self.mercLegalVm.isHidden = true
                self.settleVm.isHidden = true
                self.marketVm.isHidden = true
                break
            case .legal:
                self.mercLegalVm.isHidden = false
                self.mercMsgVm.isHidden = true
                self.settleVm.isHidden = true
                self.marketVm.isHidden = true
                break
            case .settle:
                self.settleVm.isHidden = false
                self.mercMsgVm.isHidden = true
                self.mercLegalVm.isHidden = true
                self.marketVm.isHidden = true
                break
            case .market:
                self.marketVm.isHidden = false
                self.mercMsgVm.isHidden = true
                self.mercLegalVm.isHidden = true
                self.settleVm.isHidden = true
                break
            }
        }
        
        return vm
    }()
    lazy var mercMsgVm : AuthenCompanyMercVM = {
        let vm = AuthenCompanyMercVM.init(frame: CGRect.init(x: 0, y: self.typeVm.frame.maxY+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(self.typeVm.frame.maxY+kFitWidth(10))))
        vm.photoVm.controller = self
        vm.msgVm.controller = self
        vm.msgVm.merchantType = "0"
//        vm.channel = self.channel
        vm.nextBlock = {()in
            self.nextAction()
        }
        vm.msgVm.areaCodeVm.tapBlock = {()in
            self.sendProvinceRequest()
        }
        return vm
    }()
    lazy var mercLegalVm : AuthenCompanyLegalVM = {
        let vm = AuthenCompanyLegalVM.init(frame: CGRect.init(x: 0, y: self.mercMsgVm.frame.minY, width: 0, height: self.mercMsgVm.frame.height))
        vm.isHidden = true
        vm.photoVm.controller = self
        vm.msgVm.controller = self
        vm.nextBlock = {()in
            self.nextAction()
        }
        return vm
    }()
    lazy var settleVm : AuthenCompanySettleFYVM = {
        let vm = AuthenCompanySettleFYVM.init(frame: CGRect.init(x: 0, y: self.mercMsgVm.frame.minY, width: 0, height: self.mercMsgVm.frame.height))
        vm.isHidden = true
        vm.photoVm.controller = self
        vm.msgVm.controller = self
        vm.unincorporateVM.photoVm.controller = self
        vm.unincorporateVM.msgVm.controller = self
//        vm.photoVm.updateUIForFYPublic()
        vm.nextBlock = {()in
            self.nextAction()
        }
        return vm
    }()
    lazy var marketVm : AuthenCompanyMarketVM = {
        let vm = AuthenCompanyMarketVM.init(frame: CGRect.init(x: 0, y: self.mercMsgVm.frame.minY, width: 0, height: self.mercMsgVm.frame.height))
        vm.isHidden = true
        vm.photoVm.controller = self
        vm.msgVm.controller = self
        vm.nextBlock = {()in
            self.nextAction()
        }
        vm.msgVm.marketProvinceVm.tapBlock = {()in
            self.sendProvinceRequest()
        }
        return vm
    }()
    lazy var addressPickerVm : AddressPickerVM = {
        let vm = AddressPickerVM.init(frame: .zero)
        vm.isHidden = true
        
        vm.tapBlock = {(dict)in
            //商户信息页面的地址
            if self.type == .merc{
                if self.addressPickerVm.regionType == .province{
                    AddressModel.shareInstance.addressProvinceCode = dict["regionCode"]as? String ?? ""
                    AddressModel.shareInstance.addressProvinceName = dict["regionName"]as? String ?? ""
                    self.sendCityRequest()
                }else if self.addressPickerVm.regionType == .city{
                    AddressModel.shareInstance.addressCityCode = dict["regionCode"]as? String ?? ""
                    AddressModel.shareInstance.addressCityName = dict["regionName"]as? String ?? ""
                    self.sendAreaRequest()
                }else if self.addressPickerVm.regionType == .area{
                    AddressModel.shareInstance.addressAreaCode = dict["regionCode"]as? String ?? ""
                    AddressModel.shareInstance.addressAreaName = dict["regionName"]as? String ?? ""
                    
                    self.mercMsgVm.msgVm.areaCodeVm.setLabelContent(content: "\(AddressModel.shareInstance.addressProvinceName)\(AddressModel.shareInstance.addressCityName)\(AddressModel.shareInstance.addressAreaName)")
                    AuthenCompanyMsgModel.shareInstance.dealAddressToPlaceCode()
                }
            }else if self.type == .market{
//                门店信息里面的地址
                if self.addressPickerVm.regionType == .province{
                    AddressModel.shareInstance.addressProvinceCode = dict["regionCode"]as? String ?? ""
                    AddressModel.shareInstance.addressProvinceName = dict["regionName"]as? String ?? ""
                    self.sendCityRequest()
                }else if self.addressPickerVm.regionType == .city{
                    AddressModel.shareInstance.addressCityCode = dict["regionCode"]as? String ?? ""
                    AddressModel.shareInstance.addressCityName = dict["regionName"]as? String ?? ""
                    self.sendAreaRequest()
//                    self.marketVm.msgVm.marketProvinceVm.setLabelContent(content: "\(AddressModel.shareInstance.addressProvinceName)\(AddressModel.shareInstance.addressCityName)")
//                    AuthenCompanyMsgModel.shareInstance.dealAddressToPlaceCodeForMarket()
                }else if self.addressPickerVm.regionType == .area{
                    AddressModel.shareInstance.addressAreaCode = dict["regionCode"]as? String ?? ""
                    AddressModel.shareInstance.addressAreaName = dict["regionName"]as? String ?? ""
                    
                    self.marketVm.msgVm.marketProvinceVm.setLabelContent(content: "\(AddressModel.shareInstance.addressProvinceName)\(AddressModel.shareInstance.addressCityName)\(AddressModel.shareInstance.addressAreaName)")
                    AuthenCompanyMsgModel.shareInstance.dealAddressToPlaceCodeForMarket()
                }
            }
            
        }
        vm.cancelBlock = {()in
            AddressModel.shareInstance.clearAddressMsg()
        }
        return vm
    }()
}

extension AuthenCompanyFYVC{
    func nextAction() {
        if type == .merc{
            if self.isRead {
                mercMsgVm.isHidden = true
                mercLegalVm.isHidden = false
                type = .legal
            }else if mercMsgVm.checkValue(){
                mercMsgVm.isHidden = true
                mercLegalVm.isHidden = false
                type = .legal
                sendSaveMsgRequest()
            }
        }else if type == .legal{
            if self.isRead {
                mercLegalVm.isHidden = true
                settleVm.isHidden = false
                type = .settle
            }else if mercLegalVm.checkValue(){
                mercLegalVm.isHidden = true
                settleVm.isHidden = false
                type = .settle
                sendSaveMsgRequest()
            }
        }else if type == .settle{
            if self.isRead {
                settleVm.isHidden = true
                marketVm.isHidden = false
                type = .market
            }else if settleVm.checkValue(){
                settleVm.isHidden = true
                marketVm.isHidden = false
                type = .market
                sendSaveMsgRequest()
            }
        }else if type == .market{
            if self.isRead {
                
            }else if mercMsgVm.checkValue() && mercLegalVm.checkValue() && settleVm.checkValue() && marketVm.checkValue(){
                sendSaveMsgRequest(isSubmit: true)
            }
        }
        typeVm.setTypeSelected(type: self.type)
    }
    @objc func saveAction() {
        mercMsgVm.msgVm.getValue()
        mercLegalVm.getValue()
        settleVm.getValue()
        marketVm.msgVm.getValue()
        sendSaveMsgRequest(isSubmit:false)
    }
    func saveAndNextAction() {
        mercMsgVm.msgVm.getValue()
        mercLegalVm.getValue()
        settleVm.getValue()
        marketVm.msgVm.getValue()
        sendSaveMsgRequest()
        nextAction()
    }
}
extension AuthenCompanyFYVC{
    func initUI() {
        initNavi(titleStr: "企业商户进件")
        
        self.navigationView.addSubview(saveBtn)
        view.backgroundColor = .COLOR_LIGHT_GREY
        
        view.addSubview(typeVm)
        view.addSubview(mercMsgVm)
        view.addSubview(mercLegalVm)
        view.addSubview(settleVm)
        view.addSubview(marketVm)
        
        UIApplication.shared.keyWindow?.addSubview(addressPickerVm)
        
        setConstrait()
    }
    func setConstrait() {
        saveBtn.snp.makeConstraints { make in
            make.centerY.lessThanOrEqualTo(self.naviTitleLabel)
            make.right.equalToSuperview()
            make.width.equalTo(kFitWidth(72))
            make.height.equalTo(kFitWidth(20))
        }
    }
}
extension AuthenCompanyFYVC{
    func sendProvinceRequest() {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().POST(urlString: URL_address_province, parameters: nil) { responseObject in
            DLLog(message: "sendProvinceRequest:\(responseObject)")
            
            let dataArr = responseObject["data"]as? NSArray ?? []
            self.addressPickerVm.setDataSource(dataArray: dataArr)
            self.addressPickerVm.cancelBtn.isHidden = true
            self.addressPickerVm.regionType = .province
        }
    }
    func sendCityRequest() {
        MCToast.mc_loading()
        let param:[String : String] = ["provinceCode":"\(AddressModel.shareInstance.addressProvinceCode)"]
        WHNetworkUtil.shareManager().POST(urlString: URL_address_city, parameters: param as [String : AnyObject]) { responseObject in
            DLLog(message: "sendCityRequest:\(responseObject)")
            let dataArr = responseObject["data"]as? NSArray ?? []
            self.addressPickerVm.setDataSource(dataArray: dataArr)
            self.addressPickerVm.regionType = .city
            self.addressPickerVm.cancelBtn.isHidden = false
        }
    }
    func sendAreaRequest() {
        MCToast.mc_loading()
        let param = ["cityCode":"\(AddressModel.shareInstance.addressCityCode)"]
        WHNetworkUtil.shareManager().POST(urlString: URL_address_area, parameters: param as [String : AnyObject]) { responseObject in
            DLLog(message: "sendAreaRequest:\(responseObject)")
            let dataArr = responseObject["data"]as? NSArray ?? []
            self.addressPickerVm.setDataSource(dataArray: dataArr)
            self.addressPickerVm.cancelBtn.isHidden = false
            self.addressPickerVm.regionType = .area
        }
    }
    func sendSaveMsgRequest() {
        let param = AuthenMsgParam.shared.paramsForCompanyMercMsg()
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_msg_save, parameters: param as? [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
        }
    }
    func sendSaveMsgRequest(isSubmit:Bool) {
        let param = AuthenMsgParam.shared.paramsForCompanyMercMsg()
//        if !judgePhoneNumber(phoneNum: (param["tel"]as? String ?? "")){
//            self.presentAlertVcNoAction(title: "请输入正确的手机号", viewController: self)
//            return
//        }
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_msg_save, parameters: param as? [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            if responseObject["code"]as? Int ?? 0 == 200{
                if isSubmit{
                    if UserModel.shared.posChannel == "fy" && self.isAgentEdit {
                        let vc = AuthenSetRateVC()
                        vc.phone = AuthenCompanyMsgModel.shareInstance.tel
                        vc.param = param
                        self.navigationController?.pushViewController(vc, animated: true)
                    }else{
                        self.sendCertRequest(param: param)
                    }
                }else{
                    MCToast.mc_text("信息保存成功")
                }
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "保存失败!")", viewController: self)
            }
        }
    }
    //入网
    func sendCertRequest(param:NSDictionary) {
        MCToast.mc_loading()
        let paramDict = NSMutableDictionary.init(dictionary: param)
        paramDict.setValue("0", forKey: "type")
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_user_cert, parameters: paramDict as? [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            if responseObject["code"]as? Int ?? 0 == 200{
                AuthenMiniMsgModel.shareInstance.clearMsg()
                self.presentAlertVc(confirmBtn: "确定", message: "", title: "提交成功，请等待审核。", cancelBtn: nil, handler: { action in
                    self.navigationController?.popToRootViewController(animated: true)
                }, viewController: self)
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "保存失败!")", viewController: self)
            }
        }
    }
}
